<template xmlns:el-col="http://www.w3.org/1999/html">
  <div class="app-container">
    <el-card class="box-card" style="margin-top: 0px;margin-left: 0px;margin-right: 0px">
      <div class="filter-container" style="margin-bottom: 10px;">
        <el-input
          v-model="listQuery.container"
          placeholder="发版名称"
          style="width: 300px;"
          class="filter-item"
          @keyup.enter.native="handleFilter"
        />
        <el-button
          v-waves
          class="filter-item"
          type="primary"
          style="margin-left: 10px;"
          icon="el-icon-search"
          @click="handleFilter"
        >
          搜索
        </el-button>
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-edit"
          :disabled="post === false"
          @click="handleCreate"
        >
          新增
        </el-button>
      </div>

      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column
          type="expand"
        >
          <template slot-scope="{row}">
            <el-form label-position="left" inline class="demo-table-expand">
              <template v-for="(item,key) in row.exec_list">
                <el-divider :key="key">流程ID:{{ item.id }}</el-divider>
                <el-form-item :key="key" label="更新参数">
                  <span>{{ item.params }}</span>
                </el-form-item>
                <el-form-item :key="key" label="更新状态">
                  <el-tag :type="item.status| tagFilter">{{ item.status|statusFilter }}</el-tag>
                </el-form-item>
                <el-form-item :key="key" label="输出信息">
                  <span>{{ item.output }}</span>
                </el-form-item>
                <el-form-item :key="key" label="创建时间">
                  <span>{{ item.create_time }}</span>
                </el-form-item>
                <el-form-item :key="key" label="完成时间">
                  <span>{{ item.finish_time }}</span>
                </el-form-item>
              </template>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column
          label="ID"
          prop="id"
          sortable="custom"
          align="center"
          width="80"
          :class-name="getSortClass('id')"
        >
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="执行服务" align="center">
          <template slot-scope="{row}">
            <span class="link-type">{{ row.container }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属项目" align="center">
          <template slot-scope="{row}">
            <span>{{ row.project_st }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属环境" align="center">
          <template slot-scope="{row}">
            <el-tag :type="row.env| tagFilter" effect="dark">{{ row.env|statusFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建用户" align="center">
          <template slot-scope="{row}">
            {{ row.create_user_st }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="{row}">
            <el-tag :type="row.status| tagFilter">{{ row.status|statusFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center">
          <template slot-scope="{row}">
            <i
              class="el-icon-time"
            />
            <span>{{ row.create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button
              type="primary"
              size="mini"
              :disabled="! buttonStatus(row.button,'PUT') || ! ['not_start_exec','unbond'].includes(row.status)"
              @click="handleUpdate(row)"
            >
              修改
            </el-button>
            <el-button type="warning" size="mini" :disabled="post === false" @click="handleCopy(row)">
              拷贝
            </el-button>
            <el-button
              size="mini"
              type="danger"
              :disabled="! buttonStatus(row.button,'DELETE') || ! ['not_start_exec','unbond'].includes(row.status)"
              @click="handleDelete(row,$index)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </el-card>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <FormulateForm
        ref="dataForm"
        #default="{ isValid }"
        v-model="temp"
        label-position="left"
        label-width="100px"
        style="margin-left:100px; "
        @submit="dialogStatus==='create'?createData():updateData()"
      >
        <el-row :gutter="20">
          <el-col :span="11">
            <FormulateInput
              label="服务名称"
              prop="container"
              validation="required"
              name="container"
              :validation-messages="{required: '请填写更新服务名称'}"
            />
            <FormulateInput
              style="inset-inline: auto"
              type="radio"
              label="操作环境"
              validation="required"
              prop="env"
              name="env"
              :validation-messages="{required: '请填写所属环境'}"
              :options="{prod: '生产', pre: '预生产',dev: '开发'}"
              @input="getTemplates(temp.env, temp.project)"
            />
          </el-col>
          <el-col :span="12">
            <FormulateInput
              type="select"
              label="请选择所属项目"
              validation="required"
              name="project"
              prop="project"
              :validation-messages="{required: '请填写所属项目'}"
              :options="projectList"
              @change="temp.env = '';temp.exec_list = []"
            />
            <FormulateInput
              type="textarea"
              label="备注"
              prop="node"
              name="note"
              validation="required"
              :validation-messages="{required: '请填写备注'}"
            />
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <FormulateInput
              #default="{ index }"
              type="group"
              name="exec_list"
              prop="exec_list"
              :repeatable="true"
              label="请添加子任务?"
              add-label="+ 添加子任务"
              :validation-messages="{required: '必须添加子任务'}"
              validation="required"
            >
              <div style="display: flex;">
                <FormulateInput
                  type="select"
                  name="content_type"
                  validation="required"
                  label="模板类型"
                  itemprop="content_type"
                  :options="template_list"
                  style="flex: 0.8;margin-right: 20px"
                  :validation-messages="{required: '请选择操作类型'}"
                />
                <FormulateInput
                  style="flex: 1.2"
                  type="select"
                  name="object_id"
                  validation="required"
                  itemprop="object_id"
                  :validation-messages="{required: '请选择操作模板'}"
                  :label="label(index)"
                  :options="beverageOptions(index)"
                />
              </div>
              <FormulateInput
                input-class="el-input"
                type="text"
                name="params"
                itemprop="params"
                validation="required"
                :validation-messages="{required: '操作参数必须添加！'}"
                label="参数"
              />
            </formulateinput>
          </el-col>
        </el-row>
        <el-row :gutter="20" type="flex" justify="end" style="margin-top: 20px">
          <el-col :span="2">
            <FormulateInput
              type="button"
              label="取消"
              :outer-class="(context, classes) => ['el-button--primary el-button-mini'].concat(classes)"
              @click="dialogFormVisible = false"
            />
          </el-col>
          <el-col :span="2">
            <FormulateInput
              type="submit"
              label="确认"
              :disabled="!isValid"
            />
          </el-col>
        </el-row>
      </FormulateForm>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSubtasks, deleteSubtask, updateSubtask, addSubtask, getTemplateValues
} from '@/api/subtask'
import waves from '@/directive/waves' // waves directive
import { getProjects } from '@/api/project'
import Pagination from '@/components/Pagination'
import VueFormulate from '@braid/vue-formulate'
import '/node_modules/@braid/vue-formulate/themes/snow/snow.scss'
import { deleteAuthKey } from '@/api/auth_key'

export default {
  name: 'ComplexTable',
  components: {
    Pagination,
    VueFormulate
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        'not_start_exec': '任务还未开始',
        'progressing': '任务执行中',
        'success': '任务已完成',
        'fail': '任务失败',
        'unbond': '任务还未绑定',
        'pre': '预生产',
        'dev': '开发',
        'prod': '生产'
      }
      return statusMap[status]
    },
    tagFilter(status) {
      const statusMap = {
        'not_start_exec': 'primary',
        'progressing': 'warning',
        'success': 'success',
        'fail': 'danger',
        'unbond': 'info',
        'pre': 'warning',
        'dev': 'info',
        'prod': 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      total: 0,
      temp: {
      },
      post: true,
      project: [],
      projectList: [],
      values: [{}],
      list: [],
      template_list: [],
      template_obj_list: [],
      objects: [],
      objectsList: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        sort: '-id',
        container: ''
      },
      sortOptions: [{
        label: 'ID 正序', key: '+id'
      }, {
        label: 'ID 逆序', key: '-id'
      }],
      showReviewer: false,
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改子任务',
        create: '添加子任务'
      },
      dialogPvVisible: false,
      pvData: [],
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    beverage(index) {
      return Array.isArray(this.temp.exec_list) &&
        this.temp.exec_list[index] &&
        this.temp.exec_list[index].content_type
    },
    buttonStatus(data, button) {
      if (data === undefined || data.length <= 0) {
        return false
      } else {
        return data.includes(button)
      }
    },
    label(index) {
      return this.beverage(index) ? `请选择 ${this.beverage(index)} 相关模板` : '----'
    },
    beverageOptions(index) {
      const type = this.beverage(index)
      const options = type ? this.template_obj_list[type] : {}
      const values = this.temp.exec_list[index] || {}
      const variant = values.object_id
      if (variant && !options[variant]) {
        this.temp.exec_list[index].object_id = undefined
      }
      return options
    },
    getTemplates(envParam, proParam) {
      if (envParam === '' || proParam === '') {
        this.$message.warning('选择完整的参数！')
      } else {
        if (this.dialogFormVisible === true) {
          this.temp.exec_list = []
        }
        getTemplateValues({
          'env': envParam,
          'project': proParam
        }).then(response => {
          const { data } = response
          const { tempateList, objectDict } = data
          this.template_list = tempateList
          this.template_obj_list = objectDict
        })
      }
    },
    getProjects() {
      getProjects().then(response => {
        const { data } = response
        data.map(item => {
          this.project.push(item.id)
          this.projectList.push({ 'label': item.id + ':' + item.name, 'value': item.id })
        })
        this.project = JSON.parse(JSON.stringify(this.project))
      })
    },
    getList() {
      this.listLoading = true
      // 重置选择上的空
      if (this.listQuery.container === '') {
        this.listQuery.container = undefined
      }
      getSubtasks(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.post = response.meta.post_tag

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功！',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const {
        prop, order
      } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        container: '',
        exec_list: [],
        note: '',
        project: '',
        env: '',
        create_user: '',
        create_time: '',
        finish_time: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.projectList = []
      this.template_list = []
      this.getProjects()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleCopy(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.projectList = []
      this.template_list = []
      this.getProjects()
      this.getTemplates()
      this.getTemplates(this.temp.env, this.temp.project)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      const { exec_list } = this.temp
      this.temp.exec_list = []
      exec_list.map(item => {
        item.status = 'not_start_exec'
        item.output = ''
        item.finish_time = ''
        this.temp.exec_list.push(item)
      })
    },
    createData() {
      addSubtask(this.temp).then(response => {
        const { meta } = response
        this.list.unshift(this.temp)
        this.$notify({
          title: '成功',
          message: meta.msg,
          type: 'success',
          duration: 2000
        })
        this.dialogFormVisible = false
        this.handleFilter()
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.projectList = []
      this.template_list = []
      this.getProjects()
      this.getTemplates()
      this.getTemplates(this.temp.env, this.temp.project)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    updateData() {
      updateSubtask(this.temp.id, this.temp).then(response => {
        const { meta } = response
        const index = this.list.findIndex(v => v.id === this.temp.id)
        this.list.splice(index, 1, this.temp)
        this.$notify({
          title: '成功',
          message: meta.msg,
          type: 'success',
          duration: 2000
        })
        this.dialogFormVisible = false
      })
    },
    handleDelete(row, index) {
      this.$confirm('确认都删除该密钥?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteSubtask(row.id).then(response => {
            const { meta } = response
            const { id, container } = row
            this.list.splice(index, 1)
            this.$notify({
              title: '成功',
              dangerouslyUseHTMLString: true,
              message: `
            <div>ID: ${id}</div>
            <div>子任务名称: ${container}</div>
            <div>返回信息: ${meta.msg}</div>`,
              type: 'success'
            })
            this.dialogVisible = false
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>

<style>
.demo-table-expand {
  font-size: 0;
}

.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}

.formulate-input .formulate-input-element {
  margin-bottom: 0.1em;
  max-width: 100%;
}
code {
  margin-top: 2em;
}

</style>
